package com.bailiban.spit.controller;

import com.bailiban.common.entity.PageResult;
import com.bailiban.common.entity.Result;
import com.bailiban.common.entity.StatusCode;
import com.bailiban.spit.entity.Spit;
import com.bailiban.spit.service.SpitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhulang
 * @Classname SpitController
 * @Description SpitController
 */
@RestController
@RequestMapping("spit")
public class SpitController {
    @Autowired
    private SpitService spitService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping
    public Result findAll() {
        List<Spit> all = spitService.findAll();
        return new Result(true, StatusCode.OK, "查询所有成功", all);
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable String id) {
        Spit spit = spitService.findById(id);
        return new Result(true, StatusCode.OK, "查询成功", spit);
    }

    @GetMapping("page/{parentid}")
    public Result findByParentId(String parentid, @RequestParam(value = "page", defaultValue = "1") int page, @RequestParam(value = "size", defaultValue = "5") int size) {
        Page page1 = spitService.findByParentId(parentid, page, size);
        return new Result(true, StatusCode.OK, "分页查询成功", new PageResult<Spit>(page1.getTotalElements(), page1.getContent()));
    }

    @PutMapping("{id}")
    public Result thumbup(@PathVariable String id) {
        //模拟用户1013
        String userid = "1013";
        Object obj = redisTemplate.boundValueOps("thumbup_" + userid + "_" + id).get();
        if (StringUtils.isEmpty(obj)) {
//            查询redis数据库为null，表示用户对当前id的文章没有点赞过
            spitService.thumbup(id);
            return new Result(true, StatusCode.OK, "点赞成功");
        } else {
            return new Result(false, StatusCode.REPERROR, "你已经点过赞，请勿重复操作");
        }
    }

}
